package com.twan.kotlinbase.util

import android.Manifest
import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.text.TextUtils
import android.view.View
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.tencent.imsdk.BaseConstants
import com.tencent.imsdk.v2.*
import com.tencent.qcloud.tim.demo.chat.ChatActivity
import com.tencent.qcloud.tim.demo.menu.AddMoreActivity
import com.tencent.qcloud.tim.demo.utils.Constants
import com.tencent.qcloud.tim.demo.utils.DemoLog
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo
import com.tencent.qcloud.tim.uikit.utils.ToastUtil
import com.twan.kotlinbase.app.Role
import com.twan.kotlinbase.bean.LoginBean

object MyUtils {

    //必须同时包含大小写字母及数字
    fun checkPassword(str: String): Boolean {
        var isDigit = false //定义一个boolean值，用来表示是否包含数字
        var isLowerCase = false //定义一个boolean值，用来表示是否包含字母
        var isUpperCase = false
        for (i in 0 until str.length) {
            if (Character.isDigit(str[i])) {   //用char包装类中的判断数字的方法判断每一个字符
                isDigit = true
            } else if (Character.isLowerCase(str[i])) {  //用char包装类中的判断字母的方法判断每一个字符
                isLowerCase = true
            } else if (Character.isUpperCase(str[i])) {
                isUpperCase = true
            }
        }
        val regex = "^[a-zA-Z0-9]+$"
        return isDigit && isLowerCase && isUpperCase && str.matches(Regex(regex)) && (str.length <= 16) && (str.length >= 6)
    }

    fun getLoginInfo(): LoginBean? {
        var json = SPUtils.getInstance().getString("personinfo")
        return if (json.isNullOrEmpty()) null else JsonUtil.jsonToBean(json, LoginBean::class.java)
    }

    fun isLogin(): Boolean {
        return getLoginInfo() != null
    }

    fun getToken(): String {
        return SPUtils.getInstance().getString("token")
    }

    fun getUserid(): String? {
        return getLoginInfo()?.userId
    }


    fun getRole(): Role {
        var role = SPUtils.getInstance().getInt("role", 0)
        return if (role == 0) Role.USER else Role.SERVICE_PROVIDER
    }

    fun setRole(roleIndex: Int) {
        SPUtils.getInstance().put("role", roleIndex)
    }

    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param phoneNum 电话号码
     */
    fun callPhone(context: Activity, phoneNum: String) {
        RxPermissionsUtil.requestPermission(context, Manifest.permission.CALL_PHONE) {
            var intent = Intent(Intent.ACTION_DIAL)
            intent.data = Uri.parse("tel:$phoneNum")
            context.startActivity(intent)
        }
    }

    fun copy(context: Activity, copyText: String) {
        //获取剪贴板管理器：
        var cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建普通字符型ClipData
        var mClipData = ClipData.newPlainText("Label", copyText)
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
    }

    /**
     * 发起聊天
     */
    fun chat(context: Activity, id: String?, chatTitle: String?) {
        if (id.isNullOrEmpty()) {
            ToastUtils.showShort("达人id为空")
        } else {
            //addFriend(id) {
            var chatInfo = ChatInfo()
            chatInfo.setType(V2TIMConversation.V2TIM_C2C)
            chatInfo.setId(id) //
            chatInfo.setChatName(chatTitle)
            var intent = Intent(context, ChatActivity::class.java)
            intent.putExtra(Constants.CHAT_INFO, chatInfo)
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            context.startActivity(intent)
            //}
        }
    }

    /**
     * userid  对方ID
     * verfiyMsg 验证消息,可空
     */
    fun addFriend(userid: String, verfiyMsg: String? = "", onsuccess: () -> Unit) {
        if (TextUtils.isEmpty(userid)) {
            return
        }
        val v2TIMFriendAddApplication = V2TIMFriendAddApplication(userid)
        v2TIMFriendAddApplication.setAddWording(verfiyMsg)
        v2TIMFriendAddApplication.setAddSource("android")
        V2TIMManager.getFriendshipManager().addFriend(
            v2TIMFriendAddApplication,
            object : V2TIMValueCallback<V2TIMFriendOperationResult> {
                override fun onError(code: Int, desc: String) {
                    LogUtils.e("addFriend err code = $code, desc = $desc")
                    ToastUtil.toastShortMessage("Error code = $code, desc = $desc")
                }

                override fun onSuccess(v2TIMFriendOperationResult: V2TIMFriendOperationResult) {
                    LogUtils.e("addFriend success")
                    when (v2TIMFriendOperationResult.resultCode) {
                        BaseConstants.ERR_SUCC -> onsuccess()//ToastUtil.toastShortMessage("添加成功")
                        BaseConstants.ERR_SVR_FRIENDSHIP_INVALID_PARAMETERS -> {
                            if (TextUtils.equals(
                                    v2TIMFriendOperationResult.resultInfo,
                                    "Err_SNS_FriendAdd_Friend_Exist"
                                )
                            ) {
                                //ToastUtil.toastShortMessage("已经是好友了")
                                onsuccess()
                                return
                            }
                        }
                        BaseConstants.ERR_SVR_FRIENDSHIP_COUNT_LIMIT -> ToastUtil.toastShortMessage(
                            "超过朋友数量限制"
                        )
                        BaseConstants.ERR_SVR_FRIENDSHIP_PEER_FRIEND_LIMIT -> ToastUtil.toastShortMessage(
                            "对方朋友超过限制"
                        )
                        BaseConstants.ERR_SVR_FRIENDSHIP_IN_SELF_BLACKLIST -> ToastUtil.toastShortMessage(
                            "你已将该朋友拉入黑名单"
                        )
                        BaseConstants.ERR_SVR_FRIENDSHIP_ALLOW_TYPE_DENY_ANY -> ToastUtil.toastShortMessage(
                            "用户禁用了朋友请求"
                        )
                        BaseConstants.ERR_SVR_FRIENDSHIP_IN_PEER_BLACKLIST -> ToastUtil.toastShortMessage(
                            "你已被拉黑"
                        )
                        BaseConstants.ERR_SVR_FRIENDSHIP_ALLOW_TYPE_NEED_CONFIRM -> ToastUtil.toastShortMessage(
                            "请求已发送"
                        )
                        else -> ToastUtil.toastLongMessage(v2TIMFriendOperationResult.resultCode.toString() + " " + v2TIMFriendOperationResult.resultInfo)
                    }
                }
            })
    }

    /**
     * 获取渠道名
     *
     * @param ctx 此处习惯性的设置为activity，实际上context就可以
     * @return 如果没有获取成功，那么返回值为空
     */
//    public static String getUMChannelName(Context ctx) {
//        if (ctx == null) {
//            return null;
//        }
//        String channelName = null;
//        try {
//            PackageManager packageManager = ctx.getPackageManager();
//            if (packageManager != null) {
//                //注意此处为ApplicationInfo 而不是 ActivityInfo,因为友盟设置的meta-data是在application标签中，而不是某activity标签中，所以用ApplicationInfo
//                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);
//                if (applicationInfo != null) {
//                    if (applicationInfo.metaData != null) {
//                        channelName = applicationInfo.metaData.getString("UMENG_CHANNEL");
//                    }
//                }
//            }
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        }
//        return channelName;
//    }

    fun getUMChannelName(context: Context): String {
        var channelName: String = ""
        channelName = context.packageManager?.getApplicationInfo(
            context.packageName,
            PackageManager.GET_META_DATA
        )?.metaData?.getString("UMENG_CHANNEL") ?: ""
        return channelName;
    }
}